<?php
/**
 * 后台表单输出类
 * Form.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * -------------------------------
 * 
 * @package xcs
 * @author huangdaohai <huangdaohai.2007@163.com>
 * @version V1.0
 * @access public
 */
class ContentForm extends CWidget {
	public $modelid;
	public $fields;
	public $id;
    public $catid=0;
    public $categorys=array();
    public $siteid;
	public $formValidator;
    public $data;

    public function __construct($modelid,$catid = 0,$categorys = array()) {
		$this->modelid = $modelid;
		$this->catid = $catid;
		$this->categorys = $categorys;
        // 获取字段所有字段
        $oCmsModelField = new CmsModelField();
		$this->fields = $oCmsModelField->getList(array('model_id'=>$modelid ,'isshow'=>1));
		$this->siteid = 1;
    }
	/**
	 * ContentForm::get() 获取表单字段属性数组
	 * 
	 * @param array $data 字段值数组
	 * @return array $info 含所有表单信息数据
	 */
	public function get($data = array()) {
	   $this->data = $data;
	    $info = array();   
		foreach($this->fields as $field=>$v) {
			$func = $v['form_type'];
			$value = isset($data[$field]) ? Yii::app()->common->new_html_special_chars($data[$field]) : '';
			if(!method_exists($this, $func)) continue;
			$form = $this->$func($field, $value, $v);
			if($form !== false) {
				$require = ($v['min_length']>0 || !empty($v['pattern']) || $v['isnull']==1) ? 1 : 0;
				$info[$field] = array('name'=>$v['field_name'] ,'require'=>$require,'form'=>$form, 'formtype'=>$v['form_type']);
				
			}
		}
		return $info;
	}
	/**
	 * ContentForm::text() 文本输出
	 * 
	 * @param mixed $field 字段
	 * @param mixed $value 当前值
	 * @param mixed $fieldinfo 字段信息
	 * @return string 输出input 表单字段
	 */
	public function text($field, $value, $fieldinfo) {
		extract($fieldinfo);
		$setting = Yii::app()->common->string2array($setting);
		$size = isset($setting['size']) && $setting['size']  ? $setting['size'] : 50;
		if(!$value) $value = isset($setting['defaultvalue']) && $setting['defaultvalue']  ? $setting['defaultvalue'] : '';
		$type = isset($setting['ispassword ']) ? 'password' : 'text';
        //验证属性
        $formattribute  = array();         
        if( $isnull==1 ) $formattribute[] = 'required:true';
        if( !empty($pattern) ) $formattribute[] = 'regexp:'.$pattern;
        $verify = empty($formattribute) ? '' : 'data-rules="{'.join(',',$formattribute).'}"';
		return '<input type="'.$type.'" name="info['.$field.']" id="'.$field.'" size="'.$size.'" value="'.$value.'" class="input-text" '.$verify.' />';
	}    
	/**
	 * ContentForm::textarea() 输出文本框
	 * 
	 * @param mixed $field 字段
	 * @param mixed $value 当前值
	 * @param mixed $fieldinfo 字段信息
	 * @return string 输出input 表单字段
	 */
	public function textarea($field, $value, $fieldinfo) {
		extract($fieldinfo);
		$setting = Yii::app()->common->string2array($setting);
		extract($setting);
		if(!$value) $value = $defaultvalue;
        $formattribute  = array();         
        if( $isnull==1 ) $formattribute[] = 'required:true';
        if( !empty($pattern) ) $formattribute[] = 'regexp:'.$pattern;
        $verify = empty($formattribute) ? '' : 'data-rules="{'.join(',',$formattribute).'}"';
		$str = "<textarea name='info[{$field}]' id='$field' style='width:{$width}px;height:{$height}px;' $verify";
		if($max_length) $str .= " onkeyup=\"strlen_verify(this, '{$field}_len', {$max_length})\"";
		$str .= ">{$value}</textarea>";
		if($max_length) $str .= '能输入<B><span id="'.$field.'_len">'.$max_length.'</span></B> 字符';
		return $str;
	}
    /**
     * ContentForm::editor() 输出文本编辑器
     * 
     * @param mixed $field 字段
     * @param mixed $value 当前值
     * @param mixed $fieldinfo 字段信息
     * @return string 输出表单编辑器字段
     */
    public function editor($field, $value, $fieldinfo){
        extract($fieldinfo);
        $setting = Yii::app()->common->string2array($setting);
        extract($setting);
        if( empty($value) ) $value = isset($defaultvalue) ? $defaultvalue : '';
        //验证
        $formattribute  = array();         
        if( $isnull==1 ) $formattribute[] = 'required:true';
        if( !empty($pattern) ) $formattribute[] = 'regexp:'.$pattern;
        $verify = empty($formattribute) ? '' : 'data-rules="{'.join(',',$formattribute).'}"';
        
        $this->widget('ext.kindeditor.KindEditor',array(
                                'value'=>'',
                                'name'=>$field,
                                'width'=>$width,
                                'height'=>$height,
                                'toolbar' => $toolbar ,
                                'isfunc' => true //是否是func调用
                                //'item'=>"['emoticons','|','justifyleft', 'justifycenter', 'justifyright','justifyfull','|','fontsize','forecolor','bold','italic','underline']"
                                )
                            );
        return '<textarea id="'.$field.'" name="info['.$field.']" $verify>'.$value.'</textarea>';//CHtml::textArea($field,$value);
        
    }
	/**
	 * ContentForm::catid() 输出栏目ID
	 * 
	 * @param mixed $field 字段
	 * @param mixed $value 默认值
	 * @param mixed $fieldinfo 字段信息
	 * @return string 栏目input 字段
	 */
	public function catid($field, $value, $fieldinfo) {
	   //print_r($this->categorys);exit;
       //$this->categorys
		if(!$value) $value = $this->catid;
		
        return '<input type="hidden" name="info['.$field.']" value="'.$value.'">'.@$this->categorys[$value]['cate_name'];
	}    
	/**
	 * ContentForm::title() 输出标题 (这个标题字段会单独处理一下，会加上样式设置)
	 * 
	 * @param mixed $field 字段
	 * @param mixed $value 当前值
	 * @param mixed $fieldinfo 字段信息
	 * @return string 输出表单字段
	 */
	public function title($field, $value, $fieldinfo) {
		extract($fieldinfo);
		$setting = Yii::app()->common->string2array($setting);
		$size = isset($setting['size']) && $setting['size']  ? $setting['size'] : 50;
		if(!$value) $value = isset($setting['defaultvalue']) && $setting['defaultvalue']  ? $setting['defaultvalue'] : '';
		$type = isset($setting['ispassword ']) ? 'password' : 'text';
        //验证属性
        $formattribute  = array();         
        if( $isnull==1 ) $formattribute[] = 'required:true';
        if( !empty($pattern) ) $formattribute[] = 'regexp:'.$pattern;
        $verify = empty($formattribute) ? '' : 'data-rules="{'.join(',',$formattribute).'}"';
		return '<input type="'.$type.'" name="info['.$field.']" id="'.$field.'" size="'.$size.'" value="'.$value.'" class="input-large" '.$verify.' />';
	
	}
	/**
	 * ContentForm::box() 输出选项
	 * 
	 * @param mixed $field 字段
	 * @param mixed $value 当前值
	 * @param mixed $fieldinfo 字段信息
	 * @return string 表单选项字段
	 */
	public function box($field, $value, $fieldinfo) {

		$setting = Yii::app()->common->string2array($fieldinfo['setting']);
		if($value=='') $value = isset($setting['defaultvalue']) && $setting['defaultvalue'] ? $setting['defaultvalue'] : '';
		$options = isset($setting['options']) ? explode("\n",$setting['options']) : array('允许|1');
		foreach($options as $_k) {
			$v = explode("|",$_k);
			$k = trim($v[1]);
			$option[$k] = $v[0];
		}
		$values = explode(',',$value);
		$value = array();
		foreach($values as $_k) {
			if($_k != '') $value[] = $_k;
		}
		$value = implode(',',$value);
        $setting['boxtype'] = isset($setting['boxtype']) ? $setting['boxtype'] : 'radio';
        $setting['width'] = 50;
		switch($setting['boxtype']) {
			case 'radio':
				$string = Form::radio($option,$value,"name='info[$field]' ",$setting['width'],$field);
			break;

			case 'checkbox':
				$string = Form::checkbox($option,$value,"name='info[$field][]' ",1,$setting['width'],$field);
			break;

			case 'select':
				$string = Form::select($option,$value,"name='info[$field]' id='$field' ");
			break;

			case 'multiple':
				$string = Form::select($option,$value,"name='info[$field][]' id='$field ' size=2 multiple='multiple' style='height:60px;'");
			break;
		}
		return $string;
	}
    /**
     * ContentForm::image()
     * 
     * @param mixed $field
     * @param mixed $value
     * @param mixed $fieldinfo
     * @return
     */
    public function image($field, $value, $fieldinfo){
        $setting = Yii::app()->common->string2array($fieldinfo['setting']);
        extract($setting);
        
        if( $show_type==1 ){
            $sTheme = 'default';
            $sTpl = '"<div data-url=\'{url}\' class=\'success\'>{filename}<input type=\'hidden\' value=\'{url}\' name=\'info['.$field.']\' /><input type=\'hidden\' value=\'{aid}\' name=\'aid[]\' /></div>"';
        } else {
            $sTheme = 'imageViewTheme';
            $sTpl = '"<div class=\'success\' style=\'width:240px;\'><img src=\'{url}\' width=\'240\' /> <input type=\'hidden\' value=\'{url}\' name=\'info['.$field.']\' /><input type=\'hidden\' value=\'{aid}\' name=\'aid[]\' /></div>"';
        }
        $script = 'BUI.use("bui/uploader",function (Uploader) {
      
      //添加自定义主题
      Uploader.Theme.addTheme("default", {
        elCls: "defaultTheme",
        //可以设定该主题统一的上传路径
        url: "'.Yii::app()->params['upload']['localurl'].'admin/attachment/upload",
        queue:{
          //结果的模板，可以根据不同状态进进行设置
          resultTpl: {
            "default": "<div class=\'default\'>{filename}</div>",
            "success": '.$sTpl.',
            "error": "<div class=\'error\'><span class=\'uploader-error\'>{msg}</span></div>",
            "progress": "<div class=\'progress\'><div class=\'bar\' style=\'width:{loadedPercent}%\'></div></div>"
          }
        },
        rules: {
          //文的类型
          ext: ["'.$upload_allowext.'","文件类型只能为{0}"],
          //上传的最大个数
          max: ['.$upload_max.', "文件的最大个数不能超过{0}个"],
          //文件大小的最小值,这个单位是kb
          //minSize: [10, "文件的大小不能小于{0}KB"],
          //文件大小的最大值,单位也是kb
          maxSize: ['.$upload_maxsize.', "文件大小不能大于{0}KB"]
        }
        
      });  
      //添加自定义主题
      Uploader.Theme.addTheme("imageView", {
        elCls: "imageViewTheme",
        //可以设定该主题统一的上传路径
        url: "'.Yii::app()->params['upload']['localurl'].'admin/attachment/upload",
        queue:{
          //结果的模板，可以根据不同状态进进行设置
          resultTpl: {
            "default": "<div class=\'default\'>{filename}</div>",
            "success": '.$sTpl.',
            "error": "<div class=\'error\'><span class=\'uploader-error\'>{msg}</span></div>",
            "progress": "<div class=\'progress\'><div class=\'bar\' style=\'width:{loadedPercent}%\'></div></div>"
          }
        },
        rules: {
          //文的类型
          ext: ["'.$upload_allowext.'","文件类型只能为{0}"],
          //上传的最大个数
          max: ['.$upload_max.', "文件的最大个数不能超过{0}个"],
          //文件大小的最小值,这个单位是kb
          //minSize: [10, "文件的大小不能小于{0}KB"],
          //文件大小的最大值,单位也是kb
          maxSize: ['.$upload_maxsize.', "文件大小不能大于{0}KB"]
        }
        
      });
 
      var uploader = new Uploader.Uploader({
        //指定使用主题
        theme: "'.$sTheme.'",
        render: "#J_Uploader_'.$field.'",
        //不设时使用主题配置的上传路径
        url: "'.Yii::app()->params['upload']['localurl'].'admin/attachment/upload",
        isSuccess: function(result){
          if(result && result.url){
            $(".content-upload-'.$field.'").remove();
            return true;
          }
          return false;
        }
      }).render();
      $(".content-upload-delete-'.$field.'").live("click" ,function(){
            $(this).parent().parent().remove();
        });
    });';
        //return '<div id="J_Uploader"> </div>';
        Yii::app()->getClientScript()->registerScript('uploader_'.$field ,$script,CClientScript::POS_END);
        $showimag = '';
        if( $value ){
            if($show_type==1){
                $showimag = '<div class="bui-uploader defaultTheme content-upload-'.$field.'">
                                <div class="bui-queue bui-simple-list">
                                    <ul>
                                        <li class="bui-queue-item bui-queue-item-success bui-queue-item-selected">
                                            <div class="success" data-url="'.$value.'" style="width:240px;">'.Yii::app()->common->getFileName($value).'
                                            <input type="hidden" name="info['.$field.']" value="'.$value.'">
                                            </div> 
                                            <span class="action"><span class="bui-queue-item-del content-upload-delete-'.$field.'">删除</span></span>
                                        </li>
                                    </ul>
                                </div>
                            </div>';
            } else {
                //
                $showimag = '<div class="bui-uploader imageViewTheme content-upload-'.$field.'">
                            <div class="bui-queue bui-simple-list">
                                <ul>
                                    <li class="bui-queue-item bui-queue-item-success">
                                        <div class="success" style="width:240px;">
                                            <img src="'.$value.'" width="240"> 
                                            <input type="hidden" value="'.'.$value.'.'" name="info['.$field.']">
                                        </div> 
                                        <span class="action"><span class="bui-queue-item-del content-upload-delete-'.$field.'">删除</span></span>
                                    </li>
                                </ul>
                            </div>
                        </div>';
            }
            
        }
        return '<div id="J_Uploader_'.$field.'"> </div>' .$showimag;
    }    
	/**
	 * ContentForm::datetime()
	 * 
	 * @param mixed $field
	 * @param mixed $value
	 * @param mixed $fieldinfo
	 * @return
	 */
	function datetime($field, $value, $fieldinfo) {
	   //yyyy/mm/dd HH:MM:ss
		extract(Yii::app()->common->string2array($fieldinfo['setting']));
        empty($format) && $format = 'Y-m-d';
        $formattime = str_replace(array('Y' ,'m' ,'d' ,'H' ,'i' ,'s') ,array('yyyy' ,'mm' ,'dd' ,'HH' ,'MM' ,'ss') ,$format);
        $showTime = $showtime==1?"true":"false";
        $script = 'var Calendar = BUI.Calendar
            var datepicker = new Calendar.DatePicker({
              trigger:".calendar-time",
              showTime:'.$showTime.',
              dateMask:"'.$formattime.'",
              autoRender : true
            });';
        if($value){
            $value = Yii::app()->common->formattime($format ,$value);
        } else {
            $value = Yii::app()->common->formattime($format ,time());
        }
        /*
        empty($fieldtype) && $fieldtype='int';
        empty($format) && $format='m-d';
		if($fieldtype=='int') {
			if(!$value) $value = date('Y-m-d H:i:s' ,time());
			$format_txt = $format == 'm-d' ? 'm-d' : $format;
			if($format == 'Y-m-d Ah:i:s') $format_txt = 'Y-m-d h:i:s';
			$value = date($format_txt,$value);
			
			$isdatetime = strlen($format) > 6 ? 1 : 0;
			if($format == 'Y-m-d Ah:i:s') {
				
				$timesystem = 0;
			} else {
				$timesystem = 1;
			}			
		} elseif($fieldtype=='datetime') {
			$isdatetime = 1;
			$timesystem = 1;
		} elseif($fieldtype=='datetime_a') {
			$isdatetime = 1;
			$timesystem = 0;
		}*/
        Yii::app()->getClientScript()->registerScript('datetime' ,$script,CClientScript::POS_END);
		return "<input type='text' name='info[$field]' id='$field' value='$value' class='input-normal control-text calendar calendar-time' />";
	}
    /**
     * ContentForm::keyword()
     * 
     * @param mixed $field
     * @param mixed $value
     * @param mixed $fieldinfo
     * @return
     */
    public function keyword($field, $value, $fieldinfo) {
		extract($fieldinfo);
        extract(Yii::app()->common->string2array($fieldinfo['setting']));
		if(!$value) $value = $defaultvalue;
		return "<input type='text' name='info[$field]' id='$field' value='$value' size='$size' class='input-large input-text'>";
	}
    /**
     * ContentForm::islink() 外部链接
     * 
     * @param mixed $field 
     * @param mixed $value
     * @param mixed $fieldinfo
     * @return
     */
    public function islink($field, $value, $fieldinfo) {
		if($value) {
			$url = $this->data['url'];
            $disabled = '';
			$checked = 'checked';
			$_GET['islink'] = 1;
		} else {
			$disabled = 'disabled';
			$url = $checked = '';
			$_GET['islink'] = 0;
		}
		$size = 25;
		return '<input type="hidden" name="info[islink]" value="0"><input type="text" name="linkurl" id="linkurl" value="'.$url.'" size="'.$size.'" maxlength="255" '.$disabled.' class="input-text"> <input name="info[islink]" type="checkbox" id="islink" value="1" onclick="ruselinkurl();" '.$checked.'> <font color="red">跳转链接</font>';
	}
	/**
	 * ContentForm::posid() 推荐位
	 * 
	 * @param mixed $field 字段
	 * @param mixed $value 当前值
	 * @param mixed $fieldinfo 字段信息
	 * @return string 输出input信息
	 */
	public function posid($field, $value, $fieldinfo) {
	    /*
		$setting = Yii::app()->common->string2array($fieldinfo['setting']);
		$position = getcache('position','commons');
		if(empty($position)) return '';
		$array = array();
		foreach($position as $_key=>$_value) {
			if($_value['modelid'] && ($_value['modelid'] !=  $this->modelid) || ($_value['catid'] && strpos(','.$this->categorys[$_value['catid']]['arrchildid'].',',','.$this->catid.',')===false)) continue;
			$array[$_key] = $_value['name'];
		}
		$posids = array();
		if(ROUTE_A=='edit') {
			$this->position_data_db = pc_base::load_model('position_data_model');
			$result = $this->position_data_db->select(array('id'=>$this->id,'modelid'=>$this->modelid),'*','','','','posid');
			$posids = implode(',', array_keys($result));
		} else {
			$posids = $setting['defaultvalue'];
		}
		return "<input type='hidden' name='info[$field][]' value='-1'>".form::checkbox($array,$posids,"name='info[$field][]'",'',$setting['width']);
        */
        //$array = array('1'=>'首页推荐' ,'2'=>'栏目首页推荐' ,'3'=>'栏目推荐' ,'4'=>'幻灯推荐');
        $aPosition = BasePositionModel::getAllPosition(array('model_id'=>$this->modelid ,'cate_id'=>$this->catid));
        $posids = $value;
        return "<input type='hidden' name='info[$field][]' value='-1'>".form::checkbox($aPosition,$posids,"name='info[$field][]'",'',120);
	}
 } 
?>